package com.icesoft.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.icesoft.framework.core.controller.BaseCrudRestController;
import com.icesoft.framework.core.service.BaseService;
import com.icesoft.framework.core.util.ContextHelper;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.framework.core.vo.Pagination;
import com.icesoft.system.annotation.AssociationCount;
import com.icesoft.system.dto.CompanyDTO;
import com.icesoft.system.entity.Company;
import com.icesoft.system.entity.User;
import com.icesoft.system.permission.OperationCons;
import com.icesoft.system.permission.annotation.BindPermission;
import com.icesoft.system.util.SecurityUtils;
import com.icesoft.system.vo.CompanyVO;
import com.icesoft.system.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.reflections.Reflections;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.Collator;
import java.util.*;

/**
 * 公司Controller
 *
 * @author ${author}
 * @date 230326
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@BindPermission(name = "公司管理")
@RequestMapping("/system/company")
public class CompanyController extends BaseCrudRestController<Company> {

	/**
	 * 查询ViewObject的分页数据
	 * <p>
	 * url请求参数示例: /list?field=abc&pageSize=20&pageIndex=1&orderBy=id
	 * </p>
	 *
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/query")
	@BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
	public JsonResult getViewObjectListMapping(CompanyDTO entity, Pagination pagination) throws Exception {
		return super.getViewObjectList(entity, pagination, CompanyVO.class);
	}

	/**
	 * 根据资源id查询ViewObject
	 *
	 * @param id ID
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/{id}")
	@BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
	public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
		return super.getViewObject(id, CompanyVO.class);
	}

	@GetMapping("/getUserCompany")
	@BindPermission(name = "获取当前用户公司基本信息", code = OperationCons.CODE_READ, develop = true)
	public JsonResult getUserCompany() throws Exception {
		UserVO user = SecurityUtils.getCurrentUser();
		return super.getViewObject(user.getCompanyId(), CompanyVO.class);
	}

	@GetMapping("/getCurrentDetail")
	@BindPermission(name = "获取当前用户公司详细信息", code = OperationCons.CODE_READ)
	public JsonResult getCurrentDetail() throws Exception {
		User user = SecurityUtils.getCurrentUser();
		CompanyVO company = super.getViewObject(user.getCompanyId(), CompanyVO.class).getData();
		List<Map<String, Object>> associationCountList = new ArrayList<>();
		Reflections reflections = new Reflections("com.icesoft");
		Set<Class<?>> set = reflections.getTypesAnnotatedWith(AssociationCount.class, true);
		TreeSet<Class<?>> treeSet = new TreeSet<>((class1, class2) -> {
			Collator comparator = Collator.getInstance(Locale.CHINA);
			return comparator.compare(class2.getSimpleName(), class1.getSimpleName());
		});
		treeSet.addAll(set);

		for (Class<?> entityClass : treeSet) {
			Map<String, Object> map = new HashMap<>();
			AssociationCount annotation = entityClass.getAnnotation(AssociationCount.class);
			BaseService<?> service = ContextHelper.getBaseServiceByEntity(entityClass);
			QueryWrapper<?> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("company_id", company.getId());
			long count = 0;
			if (service != null) {
				count = service.getEntityListCount(queryWrapper);
			}
			map.put("label", annotation.value());
			map.put("count", count);
			associationCountList.add(map);
		}
		company.setAssociationCountList(associationCountList);
		return JsonResult.OK(company);
	}

	/**
	 * 新建
	 *
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/create")
	@BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
	public JsonResult createEntityMapping(@Valid @RequestBody CompanyDTO dto) throws Exception {
		return super.createEntity(dto);
	}

	/**
	 * 更新
	 *
	 * @param dto
	 * @return JsonResult
	 * @throws Exception
	 */
	@PostMapping("/update/{id}")
	@BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
	public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody CompanyDTO dto) throws Exception {
		return super.updateEntity(id, dto);
	}

	/**
	 * 根据id删除资源对象
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/delete/{id}")
	@BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
	public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
		return super.deleteEntity(id);
	}
}
